package com.ruoyi.system.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.oss.entity.UploadResult;
import com.ruoyi.oss.factory.OssFactory;
import com.ruoyi.oss.service.IOssStrategy;
import com.ruoyi.system.domain.SysOss;
import com.ruoyi.system.domain.bo.SysOssBo;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.mapper.SysOssMapper;
import com.ruoyi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 文件上传 服务层实现
 *
 * @author Lion Li
 */
@RequiredArgsConstructor
@Service
public class SysOssServiceImpl implements ISysOssService {

    @Value("${upload-path.filePath}")
    private String filePath;

    @Value("${server.port}")
    private String port;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${upload-path.path}")
    private String path;


    private final SysOssMapper baseMapper;

    @Override
    public TableDataInfo<SysOssVo> queryPageList(SysOssBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysOss> lqw = buildQueryWrapper(bo);
        Page<SysOssVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    private LambdaQueryWrapper<SysOss> buildQueryWrapper(SysOssBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysOss> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getFileName()), SysOss::getFileName, bo.getFileName());
        lqw.like(StringUtils.isNotBlank(bo.getOriginalName()), SysOss::getOriginalName, bo.getOriginalName());
        lqw.eq(StringUtils.isNotBlank(bo.getFileSuffix()), SysOss::getFileSuffix, bo.getFileSuffix());
        lqw.eq(StringUtils.isNotBlank(bo.getUrl()), SysOss::getUrl, bo.getUrl());
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            SysOss::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.eq(StringUtils.isNotBlank(bo.getCreateBy()), SysOss::getCreateBy, bo.getCreateBy());
        lqw.eq(StringUtils.isNotBlank(bo.getService()), SysOss::getService, bo.getService());
        return lqw;
    }

    @Override
    public SysOss getById(Long ossId) {
        return baseMapper.selectById(ossId);
    }

    @Override
    public SysOss upload(MultipartFile file) {
        String originalfileName = file.getOriginalFilename();
        String suffix = StringUtils.substring(originalfileName, originalfileName.lastIndexOf("."), originalfileName.length());
        IOssStrategy storage = OssFactory.instance();
        UploadResult uploadResult;
        try {
            uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
        } catch (IOException e) {
            throw new ServiceException(e.getMessage());
        }
        // 保存文件信息
        SysOss oss = new SysOss();
        oss.setUrl(uploadResult.getUrl());
        oss.setFileSuffix(suffix);
        oss.setFileName(uploadResult.getFilename());
        oss.setOriginalName(originalfileName);
        oss.setService(storage.getServiceType().getValue());
        baseMapper.insert(oss);
        return oss;
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 做一些业务上的校验,判断是否需要校验
        }
        List<SysOss> list = baseMapper.selectBatchIds(ids);
        for (SysOss sysOss : list) {
            IOssStrategy storage = OssFactory.instance(sysOss.getService());
            storage.delete(sysOss.getUrl());
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public SysOss localUpload(MultipartFile file) {
        try {
            // 获取项目路径
            String property = System.getProperty("user.dir");
            // 文件旧名称
            String oldName = file.getOriginalFilename();
            // 文件后缀（文件类型）
            String suffix = FileUtil.extName(oldName);
            // 获取文件新名称
            String newName = createNewFileName(suffix);
            // 获取文件存放路径
            String path = this.createFilePath(property) + newName;

            BufferedInputStream bufferedInputStream = (BufferedInputStream) file.getInputStream();
            this.copyFile(bufferedInputStream, path);

            // 本地路径替换成url
            String replace = this.urlByFilePath(property, path);

            // 保存文件信息
            SysOss oss = new SysOss();
            oss.setUrl(replace);
            oss.setFileSuffix(suffix);
            oss.setFileName(newName);
            oss.setOriginalName(oldName);
            oss.setService("本地上传");
            baseMapper.insert(oss);
            return oss;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("文件上传失败！");
        }
    }

    /**
     * 获取文件新名字
     *
     * @param suffix
     * @return
     */
    private String createNewFileName(String suffix) {
        return IdUtil.fastSimpleUUID() + "." + suffix;
    }

    /**
     * 创建文件路径
     *
     * @param propertyPath
     * @return
     */
    private String createFilePath(String propertyPath) {
        String dateStr = DateUtil.format(new Date(), "yyyy-MM-dd");
        String path = propertyPath + filePath + File.separator + dateStr + File.separator;
        File file = new File(path);
        //如果路径不存在，新建
        if (!file.exists()) {
            file.mkdirs();
        }
        return path.replaceAll("\\\\", "/");
    }

    /**
     * 拷贝
     *
     * @param file
     * @param path
     * @throws Exception
     */
    private void copyFile(BufferedInputStream file, String path) throws Exception {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            fos = new FileOutputStream(path);
            bos = new BufferedOutputStream(fos);

            int size = 0;
            byte[] buffer = new byte[10240];
            while ((size = file.read(buffer)) != -1) {
                bos.write(buffer, 0, size);
            }
            bos.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("文件上传失败！");
        } finally {
            file.close();
            bos.close();
        }
    }

    /**
     * 文件路径替换成url
     *
     * @param property
     * @param path
     * @return
     */
    private String urlByFilePath(String property, String path) {
        String old = property + filePath;
        old = old.replaceAll("\\\\", "/");
        return path.replace(old, getUrl());
    }

    public String getUrl() {
        String ip = "";
        try {
            InetAddress address = InetAddress.getLocalHost();
            ip = address.getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        if (StringUtils.isBlank(ip)) {
            ip = "localhost";
        }
        StringBuilder url = new StringBuilder("http://" + ip + ":" + this.port);
        if (StringUtils.isNotBlank(contextPath) && !"/".equals(contextPath)) {
            url.append(contextPath);
        }
        if (StringUtils.isNotBlank(path) && !"/".equals(path)) {
            url.append(path);
        }
        return url.toString();
    }

}
